<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 提示 -->
    <el-card>
      <el-alert title="添加商品信息" center type="info" show-icon></el-alert>
      <!-- 添加 -->
      <el-steps :space="150" align-center :active="activeIndex-0" finish-status="success">
        <el-step title=" 基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form
        ref="addFormRef"
        :model="addGoodsForm"
        :rules="addGoodsRules"
        label-width="80px"
        label-position="top"
      >
        <el-tabs
          :tab-position="tabPosition"
          @tab-click="tabClick"
          v-model="activeIndex"
          :before-leave="beforeTabLeave"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addGoodsForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addGoodsForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addGoodsForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addGoodsForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                :options="catelist"
                :props="cateProps"
                v-model="addGoodsForm.goods_cat"
                clearable
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 渲染表单的item项 -->
            <el-form-item :label="item.attr_name" :key="item.attr_id" v-for="item in manyTabList">
              <!-- 复选框组 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox :label="cb" :key="i" border v-for="(cb,i) in item.checkBox_vals"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" :key="item.attr_id" v-for="item in onlyTabList">
              <!-- input框 -->
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- ation图片要上传发的api地址 -->
            <el-upload
              class="upload-demo"
              :action="uploadUrl"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headerObj"
              :on-success="handelSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor :v-model="addGoodsForm.goods_introduce"></quill-editor>
            <el-button type="primary" class="btnAdd" @click="adds">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>

      <!-- 显示tab栏 -->
    </el-card>
    <!-- 图片预览 -->
    <el-dialog title="图片预览" :visible.sync="previewVisible">
      <img :src="previewPath" class="previewImg" alt />
    </el-dialog>
  </div>
</template>
<script>
import _ from 'lodash'
export default {
  data() {
    return {
      activeIndex: '0',
      // 添加商品的表单数据对象
      addGoodsForm: {
        goods_name: '',
        // 商品所属的分类数组
        goods_cat: [],
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        //商品详情
        goods_introduce: '',
        //图片长传的
        pics: [],
        //参数列表 动态和静态
        attrs: []
      },
      //商品分类类列表
      catelist: [],
      //商品分类显示规则规则
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        childer: 'children'
      },
      tabPosition: 'left',
      //添加商品规则
      addGoodsRules: {
        goods_name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        goods_price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
        goods_weight: [{ required: true, message: '请输入商品重量', trigger: 'blur' }],
        goods_number: [{ required: true, message: '请输入商品数量', trigger: 'blur' }],
        goods_cat: [{ required: true, message: '请选择商品分类', trigger: 'blur' }]
      },
      //动态参数列表
      manyTabList: [],
      //静态参数列表
      onlyTabList: [],
      //上传图片的地址
      uploadUrl: 'http://127.0.0.1:8888/api/private/v1/upload',
      //图片上传组件的的请求头
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      //预览的绝对路径
      previewPath: '',
      previewVisible: false
    }
  },
  methods: {
    async addGoodsList() {
      const { data: res } = await this.$http.get('categories')
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类数据失败！')
      }
      this.catelist = res.data
    },
    //级联选择器发生变化
    handleChange() {
      console.log(this.addGoodsForm.goods_cat)
      if (this.addGoodsForm.goods_cat.length !== 3) {
        this.addGoodsForm.goods_cat = []
      }
    },
    //tab栏变化
    beforeTabLeave(activeName, oldActiveName) {
      // console.log('即将离开的标签页名字是：' + oldActiveName)
      // console.log('即将进入的标签页名字是：' + activeName)
      // return false
      if (oldActiveName === '0' && this.addGoodsForm.goods_cat.length !== 3) {
        this.$message.error('请先选择商品分类！')
        return false
      }
    },
    async tabClick() {
      console.log(this.activeIndex)
      if (this.activeIndex === '1') {
        // console.log('访问的是动态参数列表');
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params: { sel: 'many' }
        })
        if (res.meta.status !== 200) {
          this.$message.error('获取动态列表参数失败')
        }
        console.log(res)

        this.manyTabList = res.data
        console.log(this.manyTabList)
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals.length !== 0 ? item.attr_vals.split(',') : []
          //渲染勾选框，区分双向绑定的数组
          item.checkBox_vals = [...item.attr_vals]
        })
      }
      if (this.activeIndex === '2') {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params: { sel: 'only' }
        })
        if (res.meta.status !== 200) {
          this.$message.error('获取动态列表参数失败')
        }
        console.log(res)

        this.onlyTabList = res.data
        console.log(this.onlyTabList)
      }
    },
    //图片上传成功的钩子函数
    handelSuccess(response) {
      console.log(response)
      // 得到一个图片信息对象
      const picInfo = { pic: response.data.tmp_path }
      //将图片信息对象push
      this.addGoodsForm.pics.push(picInfo)
    },
    //预览事件
    handlePreview(file) {
      console.log(file)
      //完整路径展示图片
      this.previewPath = file.response.data.url
      this.previewVisible = true
    },
    //图片移除
    handleRemove(file) {
      console.log(file)
      //移除路径
      const filePath = file.response.data.tem_path
      //找到删除索引
      const i = this.addGoodsForm.pics.findIndex(x => {
        x === filePath
      })
      //删除图片
      this.addGoodsForm.pics.splice(i, 1)
    },
    async adds(response) {
      console.log(response)
      this.$refs.addFormRef.validate(valid => {
        if (!valid) return this.$message.error('请输入必要的选项')
      })
      //处理good  copy
      const form = _.cloneDeep(this.addGoodsForm)
      form.goods_cat = form.goods_cat.join(',')
      // 处理attr_vals 静态属性和动态参数
      console.log(this.manyTabList)

      this.manyTabList.forEach(item => {
        const newInfo = {
          arrt_id: item.attr_id,
          attr_value: item.attr_vals.join(',')
        }
        this.addGoodsForm.attrs.push(newInfo)
      })

      this.onlyTabList.forEach(item => {
        const newInfo = {
          arrt_id: item.attr_id,
          attr_value: item.attr_vals
        }
        this.addGoodsForm.attrs.push(newInfo)
      })
      //赋值
      form.attrs = this.addGoodsForm.attrs
      console.log(form)
      // 调接口 商品的名称必须是唯一的
      const { data: res } = await this.$http.post('goods', form)
      // console.log(res)
      if (res.meta.status !== 201) return this.$message.error('添加商品失败')
      this.$message.success('添加商品成功')
      this.$router.push('/goods')
    }
  },
  created() {
    this.addGoodsList()
  },
  computed: {
    cateId() {
      if (this.addGoodsForm.goods_cat.length === 3) {
        return this.addGoodsForm.goods_cat[2]
      }
      return null
    }
  }
}
</script>
<style lang="less" scoped>
.el-steps {
  margin: 10px;
}
.el-step__title {
  font-size: 12px !important;
}
.btnAdd {
  margin: 7px;
}
</style>